import React, { useEffect, useState } from "react";
import { Table, Image, Space, Button, Modal, Form, Input } from "antd";
import axios from "axios";

const ListQwer = () => {
  const [list, setList] = useState([]);
  const columns = [
    {
      key: "id",
      title: "id",
      dataIndex: "id",
    },
    {
      key: "shopName",
      title: "shopName",
      dataIndex: "shopName",
    },
    {
      key: "shopAddress",
      title: "shopAddress",
      dataIndex: "shopAddress",
    },
    {
      key: "shopImage",
      title: "shopImage",
      dataIndex: "shopImage",
      render(shopImage) {
        return <Image src={shopImage} alt="" height={30} />;
      },
    },
    {
      key: "delete",
      title: "操作",
      render(row) {
        return (
          <Space>
            <Button type="primary" danger onClick={() => handleDelete(row.id)}>
              删除
            </Button>
            <Button type="primary" onClick={() => openDialog(2, row)}>
              编辑
            </Button>
          </Space>
        );
      },
    },
  ];
  const _getList = async () => {
    const resp = await axios.get("/api/list", { params: { pageSize: 1000 } });
    console.log(resp.data);
    setList(resp.data.data.data);
  };
  const handleDelete = async (id) => {
    await axios.delete("/api/list", { params: { id } });
    _getList();
  };

  useEffect(() => {
    _getList();
  }, []);

  const [open, setOpen] = useState(false);

  // 1 ： 添加
  // 2 ： 编辑
  const [isAdd, setISAdd] = useState(1);
  const [form] = Form.useForm();
  const handleOk = async () => {
    const data = form.getFieldsValue();

    if (isAdd === 1) {
      // 添加
      await axios.put("/api/list", data);
    } else {
      // 编辑
      await axios.post("/api/list", data);
    }
    _getList();

    setOpen(false);
  };
  const openDialog = (num, row) => {
    setOpen(true);
    setISAdd(num);
    if (num === 1) {
      // 添加
      form.resetFields();
    } else {
      // 编辑
      form.setFieldsValue(row);
    }
  };

  return (
    <div>
      <h2>增删改查</h2>
      <Button onClick={() => openDialog(1)}>添加</Button>
      <Table dataSource={list} columns={columns}></Table>

      <Modal
        open={open}
        onOk={() => handleOk()}
        onCancel={() => setOpen(false)}
      >
        <Form form={form}>
          <Form.Item label="id" name="id">
            <Input disabled></Input>
          </Form.Item>
          <Form.Item label="店名" name="shopName">
            <Input></Input>
          </Form.Item>
          <Form.Item label="地址" name="shopAddress">
            <Input></Input>
          </Form.Item>
          <Form.Item label="图片" name="shopImage">
            <Input></Input>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ListQwer;
